package com.eagle.gennewdata.model;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.eagle.gennewdata.untl.GlobalsFun;
import com.eagle.gennewdata.untl.ZLibUtils;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public final class NewDaoFactory {
	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	private NewDaoFactory() {
	}

	public static PersistenceManagerFactory get() {
		return pmfInstance;
	}

	public static void close() {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		pm.close();
	}

	public static void insertAndUpdateNewData(NewRssItem itemAdd) {
		insertNewitemImg(itemAdd);

		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			long nCrc = GlobalsFun.getChecksumValue(new CRC32(),
					itemAdd.getLink());
			itemAdd.setId(nCrc);
			Key k = KeyFactory
					.createKey(NewRssItem.class.getSimpleName(), nCrc);
			itemAdd.setKey(k);
			pm.getObjectById(NewRssItem.class, k);
		} catch (Exception e) {
			// TODO: handle exception
			pm.makePersistent(itemAdd);
		} finally {
			pm.close();
		}
		
	}

	public static void insertAndUpdateImgData(NewImgItem itemAdd) {
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			long nCrc = GlobalsFun.getChecksumValue(new CRC32(),
					itemAdd.getLink());
			Key k = KeyFactory
					.createKey(NewImgItem.class.getSimpleName(), nCrc);
			itemAdd.setKey(k);
			pm.getObjectById(NewImgItem.class, k);
		} catch (Exception e) {
			// TODO: handle exception
			pm.makePersistent(itemAdd);
		} finally {
			pm.close();
		}
	}

	public static NewItem queryNewItemByID(long nID) {
		NewItem itemReturnItem = null;
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Key k = KeyFactory.createKey(NewItem.class.getSimpleName(), nID);
			itemReturnItem = pm.getObjectById(NewItem.class, k).cloneItem();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			pm.close();
		}
		return itemReturnItem;
	}

	public static NewRssItem queryNewRssItemByID(long nID) {
		NewRssItem itemReturnItem = null;
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Key k = KeyFactory.createKey(NewRssItem.class.getSimpleName(), nID);
			itemReturnItem = pm.getObjectById(NewRssItem.class, k).cloneItem();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			pm.close();
		}
		return itemReturnItem;
	}

	public static List<NewRssItem> queryNewRssItemsByTitle(String strTitle,
			int start, int end) {
		List<NewRssItem> results = null;
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Query query = pm.newQuery(NewRssItem.class);
			query.setFilter("author =='" + strTitle + "'");
			query.setOrdering("inputDate desc");
			query.setRange(start, end);
			List<NewRssItem> resultsTmp = extractedNewRssItem(query);
			results = new ArrayList<NewRssItem>();
			for (NewRssItem item : resultsTmp) {
				results.add(item.cloneItem());
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print(e.getMessage());
		} finally {
			pm.close();
		}
		return results;
	}

	public static List<NewItem> queryNewItemsByTitle(String strTitle,
			int start, int end) {
		List<NewItem> results = null;
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Query query = pm.newQuery(NewItem.class);
			query.setFilter("author =='" + strTitle + "'");
			query.setOrdering("inputDate desc");
			query.setRange(start, end);
			List<NewItem> resultsTmp = extracted(query);
			results = new ArrayList<NewItem>();
			for (NewItem item : resultsTmp) {
				results.add(item.cloneItem());
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print(e.getMessage());
		} finally {
			pm.close();
		}
		return results;
	}

	public static List<NewImgItem> queryNewImgsByTitle(int start, int end) {
		List<NewImgItem> results = null;
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Query query = pm.newQuery(NewImgItem.class);
			query.setOrdering("inputDate desc");
			query.setRange(start, end);
			List<NewImgItem> resultsTmp = extractedImg(query);
			results = new ArrayList<NewImgItem>();
			for (NewImgItem item : resultsTmp) {
				results.add(item.cloneItem());
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print(e.getMessage());
		} finally {
			pm.close();
		}
		return results;
	}

	@SuppressWarnings("unchecked")
	private static List<NewItem> extracted(Query query) {
		return (List<NewItem>) query.execute();
	}

	@SuppressWarnings("unchecked")
	private static List<NewRssItem> extractedNewRssItem(Query query) {
		return (List<NewRssItem>) query.execute();
	}

	@SuppressWarnings("unchecked")
	private static List<NewImgItem> extractedImg(Query query) {
		return (List<NewImgItem>) query.execute();
	}

	public static void deleteNewData() {
		PersistenceManager pm = null;
		try {
			pm = pmfInstance.getPersistenceManager();
			Query query = pm.newQuery(NewRssItem.class);
			List<NewRssItem> results = extractedNewRssItem(query);
			if (results.iterator().hasNext()) {
				for (NewRssItem e : results) {
					// NewRssItem itemAdd = new NewRssItem();
					// itemAdd.setId(e.getId());
					// itemAdd.setAuthor(e.getAuthor());
					// itemAdd.setContentEncoded(ZLibUtils.compress(e.getContentEncoded().getBytes()));
					// itemAdd.setGuid(e.getGuid());
					// itemAdd.setInputDate(e.getInputDate());
					// itemAdd.setLink(e.getLink());
					// itemAdd.setLogo(e.getLogo());
					// itemAdd.setNewDescription(e.getNewDescription());
					// itemAdd.setNewTitle(e.getNewTitle());
					// insertAndUpdateNewData(itemAdd);
					if (1294977343000l > e.getInputDate())
						pm.deletePersistent(e);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.print(e.getMessage());
		} finally {
			pm.close();
		}
	}

	private static void insertNewitemImg(NewRssItem itemAdd) {
		int nCount = 0;
		int nIndex = 0;
		int nIndexEnd = 0;
		int nImgStart = 0, nImgEnd = 0;
		String strImgFormatString = "<a title=\"%s\" href=\"%s\" class=\"customgal\"><img onload=\"autoresizeimage(this)\" src=\"%s\" /></a>";
		String strSearchStart = "src=\"";
		int nSearchStartLen = strSearchStart.length();
		String strSearchEnd = "\"";

		String strImgSearchStart = "<img";
		int nImgSearchStartLen = strImgSearchStart.length();
		String strImgSearchEnd1 = "/>";
		int nImgSearchEndLen1 = strImgSearchEnd1.length();
		String strImgSearchEnd2 = "</img>";
		int nImgSearchEndLen2 = strImgSearchEnd2.length();
		int nImgSearchEndLen = 0;
		
		String strChange = "";
		
		String strHtml;
		try {
			strHtml = new String(ZLibUtils.decompress(itemAdd
					.getContentEncoded()), "UTF-8");
			strHtml = strHtml.toLowerCase();
			strChange = strHtml;
			
			nImgStart = strHtml.indexOf(strImgSearchStart);
			
			while (nImgStart > 0) {
				nImgEnd = strHtml.indexOf(strImgSearchEnd1, nImgStart
						+ nImgSearchStartLen + 1);
				nImgSearchEndLen = nImgSearchEndLen1;
				if (nImgEnd < 0) {
					nImgEnd = strHtml.indexOf(strImgSearchEnd2, nImgStart
							+ nImgSearchStartLen + 1);
					nImgSearchEndLen = nImgSearchEndLen2;
				}
				
				if (nImgEnd < 0)
					break;
				
				nIndex = strHtml.indexOf(strSearchStart, nImgStart);
				
				if (nIndex > 0)
					nIndexEnd = strHtml.indexOf(strSearchEnd, nIndex
							+ nSearchStartLen + 1);
				if (nIndexEnd > 0 && nIndexEnd < nImgEnd) {
					String strImgLink = strHtml.substring(nIndex
							+ nSearchStartLen, nIndexEnd);
					if(strImgLink.indexOf("http://") < 0)
						strImgLink = itemAdd.getParentUrl() + strImgLink;
					
					if (nCount++ > 0) {
						NewImgItem itemImg = new NewImgItem();
						itemImg.setLink(strImgLink);
						itemImg.setId(itemAdd.getId());
						itemImg.setInputDate(itemAdd.getInputDate());
						itemImg.setTitle(itemAdd.getNewTitle());
						insertAndUpdateImgData(itemImg);
						String strImgHtml = String.format(strImgFormatString, itemAdd.getNewTitle(), strImgLink, strImgLink); 
						strHtml = strHtml.substring(0, nImgStart) + strImgHtml + strHtml.substring(nImgEnd + nImgSearchEndLen, strHtml.length());
						nImgEnd = nImgStart + strImgHtml.length();
					}
					
				}
				nIndex = strHtml.indexOf(strSearchStart, nIndexEnd);
				
				nImgStart = strHtml.indexOf(strImgSearchStart, nImgEnd);
			}
			if(strChange.indexOf("customgal") < 0)
				itemAdd.setContentEncoded(ZLibUtils.compress(strHtml.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}